home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / The World of Computer Software.iso / faq-xt.zip / FAQ-XT next >
Text File  |  1993-01-27  |  64KB  |  1,562 lines

  1. Newsgroups: comp.windows.x.intrinsics,comp.windows.x,news.answers
  2. Followup-To: comp.windows.x.intrinsics
  3. Reply-To: ware@cis.ohio-state.edu
  4. Subject: comp.windows.x.intrinsics Frequently Asked Questions (FAQ)
  5. Summary: Answers about the X11 Window System widgets and Xt Intrinsics library
  6. Approved: news-answers-request@MIT.Edu
  7.  
  8. Archive-name: Xt-FAQ
  9. Version: $Id: FAQ-Xt,v 1.19 92/12/08 09:13:31 ware Exp $
  10.  
  11.             The X Toolkit Intrinsics F.A.Q
  12.               A monthly posting
  13.  
  14.  
  15. This article contains the answers to some Frequently Asked Questions
  16. (FAQ) from comp.windows.x about the X Toolkit Intrinsics.  To submit
  17. questions (preferably with an answer) send email to: ware@cis.ohio-state.edu
  18.  
  19. All code fragments are public domain.  
  20.  
  21.                    Contents
  22. 0.  Xt Glossary
  23. 1.  Software Versions
  24. 2.  Related FAQ's
  25. 3.  Why does my application core dump when I use signals/alarms/cthreads?
  26. 4.  How do I use a different visual than the default?
  27. 5.  Which visual should an application use?
  28. 6.  Why do only Shell widgets have a Visual?
  29. 7.  Which visual, depth and colormap do Shells inherit?
  30. 8.  I've done all the above and I still get a BadMatch error.  Why?
  31. 9.  Why doesn't my widget get destroyed when I call XtDestroyWidget()?
  32. 10. How do I exit but still execute the DestroyCallbacks?
  33. 11. How do I resize a Shell widget?
  34. 12. Why can't XtAppAddInput() handle files?
  35. 13. What good books and magazines are there on Xt?
  36. 14. What Widgets are available?
  37. 15. What alternatives to the Intrinsics are there?
  38. 16. How do I pass a float value to XtSetValues?
  39. 17. How do I write a resource converter?
  40. 18. How do I open multiple displays?
  41. 19. What changed from R3 to R4 to R5?
  42. 20. Where are the resources loaded from?
  43. 21. What order are callbacks executed in?
  44. 22. How do I know if a widget is visible?
  45. 23. How do I reparent a widget in Xt, i.e. XtReparentWidget()?
  46. 24. Why use XtMalloc, XtFree, etc?
  47. 25. How to debug an Xt application?
  48.  
  49. The "+++" indicates the question needs more of an answer.
  50.  
  51. ----------------------------------------------------------------------
  52. 0.  Xt Glossary
  53. ----------------------------------------------------------------------
  54.  
  55. o The Xt Intrinsics implement an object oriented interface to C code
  56.   to allow useful graphical components to be created.  Included with
  57.   this are classes that provide the base functionality: Object,
  58.   RectObj, Core, Composite, Constraint, Shell, OverrideShell, WMShell,
  59.   etc.  The terms "Xt" and "Intrinsics" are used interchangeably,
  60.   however, they are used very precisely to mean a specific library of the X
  61.   window system.  In particular, it does not include the Athena,
  62.   Motif, OLIT or any other widget set.  Without further widgets the
  63.   Intrinsics are not especially useful.
  64.  
  65. o A widget refers to a user interface abstraction created via Xt.  The
  66.   precise use, is any object that is a subclass of the Core class.  It
  67.   is used loosely to refer to anything that is a subclass of the
  68.   Object class although these are more accurately called windowless
  69.   widgets or gadgets.
  70.  
  71. o Xlib is the C interface to the X11 protocol.  It is one layer below
  72.   the Xt Intrinsics.  Typically a widget uses relatively few Xlib
  73.   functions because Xt provides most such services although an
  74.   understanding of Xlib helps with problems.
  75.  
  76. ----------------------------------------------------------------------
  77. 1.  Software Versions
  78. ----------------------------------------------------------------------
  79.  
  80. The following are the latest versions of Xt based software:
  81.         _____________________________________________________________
  82.     Software    Version        Released    Next Expected
  83.         _____________________________________________________________
  84.     X11R4        patch 18            (none)
  85.     X11R5        patch 17    8/27/92        ??
  86.     Athena Widgets    (see X11R5)
  87.     Motif        1.2.1        9/92        ??
  88.     OLIT        ??        ??        ??
  89.     Xtra        2.5        6/15/92        ??
  90.     Xw        X11R4                (none)
  91.     Xcu        X11R5                (none)
  92.     fwf        3.2        6/08/92        ??
  93.         _____________________________________________________________
  94.  
  95. ----------------------------------------------------------------------
  96. 2.  Related FAQ's
  97. ----------------------------------------------------------------------
  98. David B. Lewis (uunet!craft!faq) maintains the FAQ on X.  It
  99. is posted monthly on comp.windows.x and located on export in contrib/FAQ.
  100.  
  101. Liam R. E. Quin (lee@sq.sq.com) posts an FAQ list on Open Look to 
  102. comp.windows.x.  
  103.  
  104. Jan Newmarch (jan@pandonia.canberra.edu.au) posts an FAQ list on Motif 
  105. to comp.windows.x.motif.
  106.  
  107. Peter Ware (ware@cis.ohio-state.edu) posts an FAQ list for
  108. comp.windows.x.intrinsics; it is on export in contrib/FAQ-Xt.
  109.  
  110. ----------------------------------------------------------------------
  111. 3.  Why does my application core dump when I use signals/alarms/cthreads?
  112. ----------------------------------------------------------------------
  113.  
  114. In brief, Xlib, Xt and most widget sets have no mutual exclusion for
  115. critical sections.  Any interrupt handler is likely to leave one of
  116. the above libraries in an inconsistent state -- such as all the
  117. appropriate flags not yet set, dangling pointers, in the middle of a
  118. list traversal, etc.  Note that the ANSI C standard points out that
  119. behavior of a signal handler is undefined if the signal handler calls
  120. any function other than signal() itself, so this is not a problem
  121. specific to Xlib and Xt; the POSIX specification mentions other
  122. functions which may be called safely but it may not be assumed that
  123. these functions are called by Xlib or Xt functions.
  124.  
  125. The only safe way to deal with signals is to set a flag in the
  126. interrupt handler.  This flag later needs to be checked either by a
  127. work procedure or a timeout callback.  It is incorrect to add either
  128. of these in the interrupt handler.  As another note, it is dangerous
  129. to add a work procedure that never finishes.  This effectively
  130. preempts any work procedures previously added and so they will never
  131. be called.  Another option is to open a pipe, tell the event loop
  132. about the read end using XtAppAddInput() and then the signal handler
  133. can write a byte to the write end of the pipe for each signal.
  134. However, this could deadlock your process if the pipe fills up.
  135.  
  136. Why don't the Intrinsics deal with this problem?  Primarily because it
  137. is supposed to be a portable layer to any hardware and operating
  138. system.   Is that a good enough reason -- I don't think so.
  139.  
  140.         Note: the article in The X Journal 1:4 and the example in O'Reilly
  141. Volume 6 are in error.
  142.  
  143. ----------------------------------------------------------------------
  144. 4.  How do I use a different visual than the default?
  145. ----------------------------------------------------------------------
  146.  
  147. This requires a more complicated answer than it should.  A window has
  148. three things that are visual specific -- the visual, colormap and
  149. border pixmap.  All widgets have their own Colormap and BorderPixmap
  150. resource; only shell widgets have Visual resources (another questions
  151. deals with why shells have a Visual).  The default value of these
  152. resources is CopyFromParent which does exactly what it says.  In the
  153. shell widget CopyFromParent gets evalulated as DefaultVisualOfScreen
  154. and DefaultColormapOfScreen.  When any one of the three resources is
  155. not properly set, a BadMatch error occurs when the window is
  156. created.  They are not properly set because each of the values depends
  157. on the visual being used.  
  158.  
  159. How to get this to work?  There are two parts to the answer.  The
  160. first is if you want an application to start with a particular visual
  161. and the second is if you want a particular shell within an application
  162. to start with a different visual.  The second is actually easier
  163. because the basic information you need is available.  The first is a
  164. little harder because you'll need to initialize much of the toolkit
  165. yourself in order to determine the needed information.
  166.  
  167. /*
  168.  * Some sample code to start up an application using something other
  169.  * than the default visual.
  170.  *
  171.  * To compile:
  172.  *    cc -g visual.c -o visual -lXaw -lXmu -lXt -lXext -lX11 -lm
  173.  *
  174.  * To run:
  175.  *    ./visual -geometry 300x300 -visual StaticColor -fg blue -bg yellow
  176.  *
  177.  * you need to move the mouse to get the particular visuals colormap
  178.  * to install.
  179.  */
  180.  
  181. #include <X11/Intrinsic.h>
  182. #include <X11/StringDefs.h>
  183. #include <X11/Shell.h>
  184.  
  185. typedef struct
  186. {
  187.     Visual    *visual;
  188. } OptionsRec;
  189.  
  190. OptionsRec    Options;
  191.  
  192. XtResource resources[] =
  193. {
  194.     {"visual", "Visual", XtRVisual, sizeof (Visual *),
  195.     XtOffsetOf (OptionsRec, visual), XtRImmediate, NULL},
  196. };
  197.  
  198. XrmOptionDescRec Desc[] =
  199. {
  200.     {"-visual", "*visual", XrmoptionSepArg, NULL}
  201. };
  202.  
  203.  
  204.  
  205. int
  206. main (argc, argv)
  207.     int        argc;
  208.     char        **argv;
  209. {
  210.     XtAppContext    app;        /* the application context */
  211.     Widget        top;        /* toplevel widget */
  212.     Display        *dpy;        /* display */
  213.     char        **xargv;    /* saved argument vector */
  214.     int        xargc;        /* saved argument count */
  215.     Colormap    colormap;    /* created colormap */
  216.     XVisualInfo    vinfo;        /* template for find visual */
  217.     XVisualInfo    *vinfo_list;    /* returned list of visuals */
  218.     int        count;        /* number of matchs (only 1?) */
  219.     Arg        args[10];
  220.     Cardinal    cnt;
  221.     char        *name = "test";
  222.     char        *class = "Test";
  223.  
  224.     /*
  225.      * save the command line arguments
  226.      */
  227.  
  228.     xargc = argc;
  229.     xargv = (char **) XtMalloc (argc * sizeof (char *));
  230.     bcopy ((char *) argv, (char *) xargv, argc * sizeof (char *));
  231.  
  232.     /*
  233.      * The following creates a _dummy_ toplevel widget so we can
  234.      * retrieve the appropriate visual resource.
  235.      */
  236.     cnt = 0;
  237.     top = XtAppInitialize (&app, class, Desc, XtNumber (Desc), &argc, argv,
  238.                    (String *) NULL, args, cnt);
  239.     dpy = XtDisplay (top);
  240.     cnt = 0;
  241.     XtGetApplicationResources (top, &Options, resources,
  242.                    XtNumber (resources),
  243.                    args, cnt);
  244.     cnt = 0;
  245.     if (Options.visual && Options.visual != DefaultVisualOfScreen (XtScreen (top)))
  246.     {
  247.         XtSetArg (args[cnt], XtNvisual, Options.visual); ++cnt;
  248.         /*
  249.          * Now we create an appropriate colormap.  We could
  250.          * use a default colormap based on the class of the
  251.          * visual; we could examine some property on the
  252.          * rootwindow to find the right colormap; we could
  253.          * do all sorts of things...
  254.          */
  255.         colormap = XCreateColormap (dpy,
  256.                         RootWindowOfScreen (XtScreen (top)),
  257.                         Options.visual,
  258.                         AllocNone);
  259.         XtSetArg (args[cnt], XtNcolormap, colormap); ++cnt;
  260.  
  261.         /*
  262.          * Now find some information about the visual.
  263.          */
  264.         vinfo.visualid = XVisualIDFromVisual (Options.visual);
  265.         vinfo_list = XGetVisualInfo (dpy, VisualIDMask, &vinfo, &count);
  266.         if (vinfo_list && count > 0)
  267.         {
  268.             XtSetArg (args[cnt], XtNdepth, vinfo_list[0].depth);
  269.             ++cnt;
  270.             XFree ((XPointer) vinfo_list);
  271.         }
  272.     }
  273.     XtDestroyWidget (top);
  274.  
  275.  
  276.     /*
  277.      * Now create the real toplevel widget.
  278.      */
  279.     XtSetArg (args[cnt], XtNargv, xargv); ++cnt;
  280.     XtSetArg (args[cnt], XtNargc, xargc); ++cnt;
  281.     top = XtAppCreateShell ((char *) NULL, class,
  282.                 applicationShellWidgetClass,
  283.                 dpy, args, cnt);
  284.  
  285.     /*
  286.      * Display the application and loop handling all events.
  287.      */
  288.     XtRealizeWidget (top);
  289.     XtAppMainLoop (app);
  290.     return (0);
  291. }
  292.  
  293. ----------------------------------------------------------------------
  294. 5.  Which visual should an application use?
  295. ----------------------------------------------------------------------
  296.  
  297. This is a point that can be argued about but one opinion is there is
  298. no way for an application to know the appropriate visual -- it has to
  299. be specified by the user.  If you disagree with this then your
  300. application probably falls into the category of always using the
  301. default visual or it is hardware specific and expects some particular
  302. visual such as 24bit TrueColor with an OverlayPlane extension (or some
  303. such).
  304.  
  305. Why?  No application runs in isolation.  Depending on the way a server
  306. allocates resources I may not always want your application to run in
  307. TrueColor mode if it is going to mess up my other applications.  I may
  308. be very upset if it chooses to run in GreyScale instead of PsuedoColor
  309. or just monochrome.
  310.  
  311. As an example, on a low end color Sun server there are many different
  312. possible visuals: monochrome, 256 entry colormap, static gray, static
  313. color, and a 3/3/2 TrueColor.  The SGI Iris's offer all the above 
  314. plus 12 bit TrueColor, 24 bit TrueColor, an Overlay Plane.
  315.  
  316. ----------------------------------------------------------------------
  317. 6.  Why do only Shell widgets have a Visual?
  318. ----------------------------------------------------------------------
  319.  
  320. This is strictly by convention.  It makes it possible for an arbitrary
  321. widget to know that the visual it uses can be found by looking for the
  322. shell widget that is its ancestor and obtaining the visual of that
  323. shell.
  324.  
  325. A widget can have its own visual resource.  If it does, it must have
  326. its own realize method to use the visual when it calls
  327. XCreateWindow().  You should also make this a resource that can be
  328. obtained with XtGetValues() so other widgets can find it.  A
  329. reasonable value is probably XtNvisual.
  330.  
  331. ----------------------------------------------------------------------
  332. 7.  Which visual, depth and colormap do Shells inherit?
  333. ----------------------------------------------------------------------
  334.  
  335. The default value for these resources are set to CopyFromParent.  This
  336. is interpreted as the DefaultColormapOfScreen(), DefaultDepthOfScreen()
  337. and the default visual of the screen if the widget has no parent -- i.e.
  338. it is an applicationShellWidgetClass and the root of your widget tree.
  339.  
  340. If the parent of the widget is not null, then the shell copies
  341. colormap and depth from its parent and uses CopyFromParent as the
  342. visual.
  343.  
  344. ----------------------------------------------------------------------
  345. 8.  I've done all the above and I still get a BadMatch error.  Why?
  346. ----------------------------------------------------------------------
  347.  
  348. Some resource converters improperly cache references.  This was
  349. especially true of X11R3 and earlier versions of Motif.
  350.  
  351. ----------------------------------------------------------------------
  352. 9.  Why doesn't my widget get destroyed when I call XtDestroyWidget()?
  353. ----------------------------------------------------------------------
  354.  
  355. See section 2.8 of the Xt specification.
  356.  
  357. It eventually does get destroyed, just not immediately.  The
  358. Intrinsics destroy a widget in a two-phase process.  First it and all
  359. of its children have a flag set that indicate it is being destroyed.
  360. It is then put on a list of widgets to be destroyed.  This way any
  361. pending X events or further references to that widget can be cleaned
  362. up before the memory is actually freed.  The second phase is then
  363. performed after all callbacks, event handlers, and actions have
  364. completed, before checking for the next X event.  At this point the
  365. list is traversed and each widget's memory is actually free()'d, among
  366. other things.
  367.  
  368. As some further caveats/trivia, the widgets may be destroyed if the
  369. Intrinsics determine that they have no further references to the
  370. widgets on the list.  If so, then the phase 2 destruction occurs
  371. immediately.  Also, if nested event loops are used, widgets placed on
  372. the destroy list before entering the inner event loop are not
  373. destroyed until returning to the outer event loop.
  374.  
  375. ----------------------------------------------------------------------
  376. 10. How do I exit but still execute the DestroyCallbacks?
  377. ----------------------------------------------------------------------
  378.  
  379. The problem is if a simple and entirely reasonable approach to exiting
  380. an application is used, such as calling exit() directly, then a widget
  381. may not have a chance to clean up any external state -- such as open
  382. sockets, temporary files, allocated X resources, etc.  (this code for
  383. simplicity reasons assumes only a single toplevel widget):
  384.  
  385.  
  386.     Widget
  387.     ToplevelGet (gw)
  388.         Widget        gw;        /* widget to find toplevel */
  389.     {
  390.         Widget        top;
  391.  
  392.         for (top = gw; XtParent (top); top = XtParent (top))
  393.             /* empty */;
  394.         return (top);
  395.     }
  396.  
  397.     void
  398.     ExitCallback (gw, closure, call_data)
  399.         Widget        gw;        /* widget */
  400.         XtPointer    closure;    /* data the app specified */
  401.         XtPointer    call_data;    /* widget specific data */
  402.     {
  403.         Widget        toplevel;
  404.  
  405.         toplevel = ToplevelGet (gw);
  406.         XtUnmapWidget (toplevel);    /* make it disappear quickly */
  407.         XtDestroyWidget (toplevel);
  408.         exit (0);
  409.     }
  410.  
  411. One can see that the above code exit's immediately after destroying
  412. the toplevel widget.  The trouble is the phase 2 destruction may never
  413. occur.  
  414.  
  415. This works for most widgets and most applications but will not work
  416. for those widgets that have any external state.  You might think that
  417. since it works now it will always work but remember that part of the
  418. reason an object oriented approach is used is so one can be ignorant
  419. of the implementation details for each widget.  Which means that the
  420. widget may change and someday require that some external state is
  421. cleaned up by the Destroy callbacks.
  422.  
  423. One alternative is to modify ExitCallback() to set a global flag and
  424. then test for that flag in a private event loop.  However, private
  425. event loops are frowned upon because it tends to encourage sloppy, and
  426. difficult to maintain practices.
  427.  
  428. Try the following code instead.
  429.  
  430.     #include <X11/Intrinsic.h>
  431.  
  432.     extern Widget ToplevelGet (
  433.     #if NeedFunctionPrototypes
  434.         Widget        gw
  435.     #endif
  436.     );
  437.  
  438.     extern Boolean ExitWorkProc (
  439.     #if NeedFunctionPrototypes
  440.         XtPointer    closure
  441.     #endif
  442.     );
  443.  
  444.     extern void ExitCallback (
  445.     #if NeedFunctionPrototypes
  446.         Widget        gw,
  447.         XtPointer    closure,
  448.         XtPointer    call_data
  449.     #endif
  450.     );
  451.  
  452.     Widget
  453.     ToplevelGet (gw)
  454.     Widget        gw;        /* widget to find toplevel */
  455.     {
  456.         Widget        top;
  457.  
  458.         for (top = gw; XtParent (top); top = XtParent (top))
  459.             /* empty */;
  460.         return (top);
  461.     }
  462.  
  463.  
  464.     void
  465.     ExitCallback (gw, closure, call_data)
  466.     Widget        gw;        /* widget */
  467.     XtPointer    closure;    /* data the app specified */
  468.     XtPointer    call_data;    /* widget specific data */
  469.     {
  470.         Widget        toplevel;
  471.  
  472.         toplevel = ToplevelGet (gw);
  473.         XtUnmapWidget (toplevel);    /* make it disappear quickly */
  474.         XtDestroyWidget (toplevel);
  475.         XtAppAddWorkProc (XtWidgetToApplicationContext (gw),
  476.                   ExitWorkProc, (XtPointer) NULL);
  477.     }
  478.  
  479.     Boolean
  480.     ExitWorkProc (closure)
  481.         XtPointer    closure;
  482.     {
  483.         exit (0);
  484.         /*NOTREACHED*/
  485.     }
  486.  
  487.  
  488. ExitCallback() adds a work procedure that will get called when the
  489. application is next idle -- which happens after all the events are
  490. processed and the destroy callbacks are executed.
  491.  
  492. ----------------------------------------------------------------------
  493. 11. How do I resize a Shell widget?
  494. ----------------------------------------------------------------------
  495.  
  496. After it is realized, one doesn't resize a Shell widget.  The proper
  497. thing is to resize the currently managed child of the Shell widget
  498. using XtSetValues().  The geometry change is then propagated to the
  499. Shell which asks the window manager which may or may not allow the
  500. request.  However, the Shell must have the resource
  501. XtNallowShellResize set to True otherwise it will not even ask the
  502. window manager to grant the request and the Shell will not resize.
  503.  
  504. To change the position of a Shell, use XtSetValues() on the Shell, not
  505. the child, and within the limits of the window manager it should be granted.
  506.  
  507. ----------------------------------------------------------------------
  508. 12. Why can't XtAppAddInput() handle files?
  509. ----------------------------------------------------------------------
  510.  
  511. It does, however Unix semantics for when I/O is ready for a file does
  512. not fit most peoples' intuitive model.  In Unix terms a file
  513. descriptor is ready for reading whenever the read() call would not
  514. block, ignoring the setting of optional flags that indicate not to
  515. block.  This works as expected for terminals, sockets and pipes.  For
  516. a file the read() will always return but the return indicates an EOF
  517. -- i.e. no more data.  The result is the code in the Intrinsics always
  518. calls the input handler because it always thinks something is about to
  519. be read.  The culprit is the select() system call or on SYSV based
  520. OS's it is the poll() system call.
  521.  
  522. How to get around this on a Unix system?  The best approach is to use
  523. another process to check for available input on the file.  Use a pipe
  524. to connect the application with this other process and pass the file
  525. descriptor from the pipe to XtAppAddInput().  A suitable program on
  526. BSD systems is "tail -f filename".
  527.  
  528. It's rumored that select() on some systems is not _completely_
  529. reliable.  In particular:
  530.  
  531.     - IBM AIX 3.1: this is one where it would work for a while
  532.       (several thousand times) and then stop until some other
  533.       event woke it up. This seemed to be the result of a race
  534.       condition in the Kernel.  IBM claims to have a fix for this.
  535.  
  536.     - Pyramid, doesn't work at all.
  537.  
  538.     - Ultrix (and possibly others where pipes are implemented as
  539.       sockets), wasn't completely broken, but although the writing
  540.       side wrote in 512 byte blocks the reading side received it
  541.       all broken up as if it was being put into the pipe a byte at
  542.       a time.  You can waste a lot of time by reading small blocks
  543.       (get raound it by detecting the situation and having
  544.       select() ignore the pipe for 10 mseconds - by then it had
  545.       been given the whole block).
  546.  
  547.  
  548. Note that all the above descriptions used Unix terminology such as
  549. read(), file descriptor, pipes, etc.  This is an OS dependent area and
  550. may not be identical on all systems.  However the Intrinsic designers
  551. felt it was a common enough operation that it should be included with
  552. part of the toolkit.  Why they didn't also deal with signals at this
  553. point I don't know.
  554.  
  555. ----------------------------------------------------------------------
  556. 13. What good books and magazines are there on Xt?
  557. ----------------------------------------------------------------------
  558.  
  559. I have a favorite that is the definitive reference.  To my perspective
  560. it offers a reasonable introduction but also goes into the full
  561. details of the Intrinsics.  When I started using it I was already
  562. familiar with Xt and the concepts behind it, so newcomers may or may
  563. not find it useful.  I've always found it accurate and complete, which
  564. means its a 1000 pages.
  565.  
  566. Asente, Paul J., and Swick, Ralph R., "X Window System Toolkit, The
  567.     Complete Programmer's Guide and Specification", Digital Press,
  568.     1990, ISBN 1-55558-051-3, order number EY-E757E-DP; and by
  569.     Prentice-Hall, ISBN 0-13-972191-6. Also available through DEC
  570.     Direct at 1-800-DIGITAL.
  571.  
  572. The other book I commonly recomend to novices is:
  573.  
  574. Young, Doug. "The X Window System: Applications and Programming with
  575.     Xt (Motif Version)," Prentice Hall, 1989 (ISBN 0-13-497074-8).
  576.     (ISBN 0-13-972167-3)
  577.  
  578. And of course O'Reilly has an entire series of manuals on X and Xt.
  579. O'Reilly ordering is 800-998-9938.  In particular, Volume 5 is an Xt
  580. reference done in manual page style.  The 3rd edition is extensively
  581. overhauled and goes far beyond the MIT manual pages.  I'm finding it
  582. very useful.  In particular, the permutted index and references to
  583. other manual pages help a great deal in chasing down related
  584. information.
  585.  
  586. I read two periodicals, "The X Resource" and the "The X Journal".
  587. These are the only two dealing specifically with X.  "The X Resource"
  588. is published quarterly, by O'Reilly, with one of the issues being the
  589. MIT X Consortium Technical Conference Proceedings.  There is no
  590. advertising.  I've found it informative with pretty good depth.  For
  591. orders, call 1-800-998-9938, or email cathyr@ora.com.  For editorial
  592. matters, email adrian@ora.com.  Table of contents are posted at
  593. math.utah.edu in ~ftp/pub/tex/bib in TeX form and on ftp.uu.net in
  594. ~ftp/published/oreilly/xresource in ASCII form.
  595.  
  596.  
  597. "The X Journal" is a bimonthly trade rag with lots of advertising.
  598. The articles are informative and oriented toward a less technical
  599. audience.  I read it more to see what's going on then with an
  600. expectation of learning a great deal (but remember, I represent a
  601. fairly small percentage of people).  Also, they have a pretty good
  602. collection of people on the advisory board and as columnists.  Call
  603. (908) 563-9033.
  604.  
  605. ----------------------------------------------------------------------
  606. 14. What Widgets are available?
  607. ----------------------------------------------------------------------
  608.  
  609. There are three popular widget sets:
  610.  
  611. Athena    - The set provided with X11.  This is sufficient for most
  612.       purposes but is on the ugly side.  Recently, a 3d look is
  613.       available for ftp on export.lcs.mit.edu:/contrib/Xaw3d.tar.Z.
  614. Motif    - From OSF available for a license fee and commonly shipped on
  615.       many workstation vendors platforms (almost everyone but
  616.       Sun).  It looks good and works well but personally I think
  617.       it is poorly implemented.
  618. OLIT    - The Open Look Intrinsics Toolkit is a set of widgets
  619.       implementing Sun's Open Look specification.  Developed by
  620.       AT&T.  I've never used it so can't comment on its quality.
  621.       I've heard rumours that it is a pain to actually get.
  622.  
  623. In addition the following collection of widgets are also available:
  624.  
  625. Xtra    - a library of widgets for sale from Graphical Software
  626.       Technology (310-328-9338).  It includes bar graph, stacked
  627.       bar graph, line graph, pie chart, xy plot, hypertext, help,
  628.       spreadsheet, and data entry form widgets.  I've never seen
  629.       them so I can't comment.
  630. FWF    - The Free Widget Foundation is attempting to collect a set of
  631.       freely available widgets.  Included are a Pixmap editor,
  632.       FileDialog, and a few others.  The current set of widgets
  633.       can be obtained via anonymous ftp from the machine
  634.       a.cs.uiuc.edu (128.174.252.1) in the file pub/fwf.shar.Z.
  635. Xcu    - The Cornell University widgets from Gene Dykes.  One of the
  636.       early widget sets released.  Provides a nice appearance for
  637.       buttons and has a mini command language.  Probably not so
  638.       widely used.
  639. Xs    - The Sony widget set.  This was around during R3 days but
  640.       seemed to disappear.  It looked like it had promise.
  641. Xw    - The HP widgets.  The precursor to Motif.  Originally written
  642.       for R3 there exists diffs to get it to work under R4 & R5.
  643.       Again, a pretty good widget set but has more or less died.
  644.       The precursor to this was the Xray toolkit which was
  645.       originally implemented for X10R4 and apparently provided
  646.       much experience for the designers of Xt.
  647. Xo    - A widget set I'm working on.  It's still primitive but you
  648.       can give it a try in archive.cis.ohio-state.edu:pub/Xo/*
  649.  
  650. The following specialized widgets are also available:
  651.  
  652. Tbl    - Implements a tabular layout of widgets.  Supports Motif
  653.       widgets as children.  Part of Wcl.
  654. Plots    - The Athena Plotting widgets (not the Athena widgets).
  655.       Contact gnb@bby.oz.au or joe@Athena.MIT.EDU.
  656.  
  657. ----------------------------------------------------------------------
  658. 15. What alternatives to the Intrinsics are there?
  659. ----------------------------------------------------------------------
  660.  
  661.     __________________________________________
  662.     Name        Language    Vendor
  663.     __________________________________________
  664.     Xview        C        Sun
  665.     OI        C++        ParcPlace
  666.     Interviews    C++        Stanford
  667.     __________________________________________
  668.  
  669.  
  670. However much I like C and admire the skill in both designing and
  671. implementing the Intrinsics, hopefully some alternative will develop
  672. in the next 3-5 years that uses an object oriented language.  Keep
  673. your eyes open and expect some change about the same time a language
  674. other than C _starts_ gaining acceptance.
  675.  
  676. ----------------------------------------------------------------------
  677. 16. How do I pass a float value to XtSetValues?
  678. ----------------------------------------------------------------------
  679.  
  680. First, what is going wrong is the structure for an Arg is (essentially)
  681.     typdef struct
  682.     {    
  683.         String    name;
  684.         long    value;
  685.     } Arg;
  686.  
  687. and the code:
  688.     Arg    arg;
  689.  
  690.     XtSetArg (arg, "name", 3.2)
  691.  
  692. expands to
  693.     Arg    arg;
  694.  
  695.     arg.name = "name";
  696.     arg.value = 3.2;
  697.  
  698. you can see that with normal C type conversions, the arg.value
  699. gets the integer "3" instead of the floating point value "3.2".  When
  700. the value is copied into the widget resource, the bit pattern is
  701. wildly different than that required for a floating point value.  So,
  702. how to get around this?
  703.  
  704. The following macro is from the Athena widgets document and I am now
  705. recomending it over the previous suggestions.
  706.  
  707. #define XtSetFloatArg(arg, n, d) \
  708.     if (sizeof(float) > sizeof(XtArgVal)) { \
  709.         XtSetArg(arg, n, &(d)); \
  710.     } else { \
  711.         XtArgVal *ld = (XtArgVal *)&(d); \
  712.         XtSetArg(arg, n, *ld); \
  713.     }
  714.  
  715.  
  716. ----------------------------------------------------------------------
  717. 17. How do I write a resource converter?
  718. ----------------------------------------------------------------------
  719.  
  720. Courtesy of Rich Thomson (rthomson@dsd.es.com):
  721.  
  722. The following discussion of resource converters assumes R4 (or R5)
  723. Intrinsics.  Resource converters changed between R3 and R4 to allow
  724. for destructors and caching of converted values.
  725.  
  726. There are several main types of resource converters:
  727.  
  728.     string to data type
  729.     data type to string
  730.     data type to data type
  731.  
  732. i) string to data type
  733.     Usually a string to data type converter has a fixed set of strings
  734.     that will be converted to data type values.  This is most often
  735.     used to map enumerated names to enumerated values:
  736.  
  737.     Name        Value
  738.     "True"        1
  739.     "False"        0
  740.  
  741.     In this case, the string to data type converter needs to compare
  742.     the resource value to the list of fixed strings.  This is most
  743.     readily accomplished by the use of the "quark" mechanism of the
  744.     resource manager.  The resource value is turned into a quark,
  745.     which is a unique representation of the string that fits into a
  746.     single word.  Then the resource quark is compared against the
  747.     quarks for the fixed strings representing the enumerated values.
  748.  
  749.     If there are many enumerated strings in the converter (or many
  750.     converters, each with a small number of enumeration strings), then
  751.     a global initialization routine might be used to turn all the
  752.     resource strings into quarks.  That way, the first time one of
  753.     these converters is used, the strings will be turned into quarks
  754.     and held in static variables for use in the next invocation of one
  755.     of the converters.
  756.  
  757. ii) data type to string
  758.     This type of converter is slightly easier than the string to data
  759.     type converters since the use of quarks isn't necessary.  Instead,
  760.     the data type value is simply converted to a string value,
  761.     probably by the use of sprintf.
  762.  
  763.     Data type to string converters are useful for applications that
  764.     wish to convert an internal data type value into a string so that
  765.     they can write out a valid resource specification to a file.  This
  766.     mechanism can be used to provide a "snapshot" of application state
  767.     into a file.  This snapshot can be used to restore the program to
  768.     a known state via the usual X resource database mechanisms.
  769.  
  770.     If you are taking the trouble to write a string to data type
  771.     converter, it isn't much extra effort to write the data type to
  772.     string converter.  Writing both at the same time helps to ensure
  773.     that they are consistent.
  774.  
  775. iii) data type to data type
  776.     This type of converter is used to convert an existing data type
  777.     value to another data type.  For instance, an X pixel value can be
  778.     converted to an RGB data type that contains separate fields for
  779.     red, green and blue.
  780.  
  781.  
  782. The type signature for a resource converter is as follows:
  783.  
  784. typedef Boolean (*XtTypeConverter)(Display *, XrmValuePtr, Cardinal *,
  785.     XrmValuePtr, XrmValuePtr, XtPointer *);
  786.     Display *dpy;
  787.     XrmValuePtr args;
  788.     Cardinal *num_args;
  789.     XrmValuePtr fromVal;
  790.     XrmValuePtr toVal;
  791.     XtPointer *converter_data;
  792.  
  793. When the converter is invoked, the "fromVal" argument points to the source
  794. X resource manager value and the "toVal" argument points to the
  795. destination X resource manager value.  The "converter_data" argument
  796. is an opaque pointer to some converter-specific data that is specified
  797. when the converter is registered.  The "args" and "num_args" arguments
  798. allow extra information to be passed to the converter when it is
  799. invoked.  For instance, the Pixel to RGB structure converter discussed
  800. above would need colormap and visual arguments in which to lookup the
  801. Pixel to obtain the RGB values corresponding to that pixel.
  802.  
  803. Care must be taken with the "toVal" argument.  An XrmValue has the
  804. following type definition and specifies a size and location for a
  805. converted value:
  806.  
  807. typedef struct {
  808.     unsigned int    size;
  809.     caddr_t         addr;
  810. } XrmValue, *XrmValuePtr;
  811.  
  812. When the converter is invoked, the address may point to a location of
  813. the given size for the converted value or the location can be NULL.
  814. In the former case, the converter should ensure that the size of the
  815. destination area is large enough to handle the converted value.  If
  816. the destination area is not large enough, then the converter should
  817. set the size to the amount of space needed and return False.  The
  818. caller can then ensure that enough space is allocated and reinvoke the
  819. converter.  If the size is large enough, then the converter can simply
  820. copy the converted value into the space given and return True.
  821.  
  822. If the location is NULL, then the converter can assign the location to
  823. the address of a static variable containing the converted value and
  824. return True.
  825.  
  826. When writing a group of converters, this code is often repeated and it
  827. becomes convenient to define a macro:
  828.  
  829.     #define DONE(var, type) \
  830.       if (toVal->addr) \
  831.     { \
  832.       if (toVal->size < sizeof(type)) \
  833.         { \
  834.           toVal->size = sizeof(type); \
  835.           return False; \
  836.         } \
  837.       else \
  838.         *((type *) toVal->addr) = var; \
  839.     } \
  840.       else \
  841.     toVal->addr = (caddr_t) &var; \
  842.       toVal->size = sizeof(type); \
  843.       return True;
  844.  
  845.     #define DONESTR(str) \
  846.       if (toVal->addr && toVal->size < sizeof(String)) \
  847.     { \
  848.       toVal->size = sizeof(String); \
  849.       return False; \
  850.     } \
  851.       else \
  852.     toVal->addr = (caddr_t) str; \
  853.       toVal->size = sizeof(String); \
  854.       return True;
  855.  
  856. Inside the converter, it is a good idea to perform a little safety
  857. checking on the "num_args" and "args" arguments to ensure that your
  858. converter is being called properly.
  859.  
  860. Once you have written your converter, you need to register it with the
  861. Intrinsics.  The Intrinsics invokes resource converters when creating
  862. widgets and fetching their resource values from the resource database.
  863.  
  864. To register a converter with a single application context, use
  865. XtAppSetTypeConverter:
  866.  
  867. void XtAppSetTypeConverter(context, from, to, converter, args, num_args,
  868.     cache, destructor)
  869.     XtAppContext context;
  870.     String from;
  871.     String to;
  872.     XtTypeConverter converter;
  873.     XtConvertArgList args;
  874.     Cardinal num_args;
  875.     XtCacheType cache;
  876.     XtDestructor destructor;
  877.  
  878. To register a converter with all application contexts, use
  879. XtSetTypeConverter:
  880.  
  881. void XtSetTypeConverter(from, to, converter, args, num_args,
  882.     cache, destructor)
  883.     String from;
  884.     String to;
  885.     XtTypeConverter converter;
  886.     XtConvertArgList args;
  887.     Cardinal num_args;
  888.     XtCacheType cache;
  889.     XtDestructor destructor;
  890.  
  891. In the R3 Intrinsics, there were the routines XtAppAddConverter and
  892. XtAddConverter; these have been superseded by XtAppSetTypeConverter
  893. and XtSetTypeConverter.  Whenever possible, the newer routines should be
  894. used.
  895.  
  896. When a converter is registered with the Intrinsics, a "cache" argument
  897. specifies how converted resource values are to be cached:
  898.  
  899.     XtCacheNone        Don't cache any converted values
  900.     XtCacheAll        Cache all converted values
  901.     XtCacheByDisplay    Cache converted values on a per display basis
  902.  
  903. Caching converted values that require a round-trip to the server is a
  904. good idea (for instance string to Pixel conversions).
  905.  
  906. The "destructor" argument is a routine that is invoked then the
  907. resource is destroyed, either because its cached reference count has
  908. been decremented to zero or because the widget owning the value is
  909. being destroyed.  XtDestructor has the following type definition:
  910.  
  911. typedef void (*XtDestructor)(XtAppContext, XrmValuePtr, XtPointer,
  912.     XrmValuePtr, Cardinal *);
  913.     XtAppContext context;
  914.     XrmValuePtr to;
  915.     XtPointer converter_data;
  916.     XrmValuePtr args;
  917.     Cardinal *num_args;
  918.  
  919. The destructor is invoked to free any auxiliary storage associated
  920. with the "to" argument, but does not actually free the storage pointed
  921. to by the "to" argument itself (to->addr).  The destructor is passed
  922. the extra arguments that were passed to the converter when the
  923. conversion was performed (for instance, colormap and visual arguments
  924. for the string to Pixel converter since the destructor would need to
  925. free the allocated Pixel from the colormap) as well as the private
  926. data passed in when the converter was registered.
  927.  
  928. Sample converter code can be found in the following files in the MIT
  929. R5 distribution:
  930.  
  931.     mit/lib/Xt/Converters.c
  932.     contrib/lib/PEXt/Converters.c
  933.     contrib/lib/PEXt/Converters.h
  934.  
  935. ----------------------------------------------------------------------
  936. 18. How do I open multiple displays?
  937. ----------------------------------------------------------------------
  938.  
  939. See "Multi-user Application Software Using Xt", The X Resource, Issue 3,
  940. (Summer 1992) by Oliver Jones for a complete coverage of the issues
  941. involved.  Most of this answer is based on that article.  In a
  942. nutshell, one uses XtOpenDisplay() to add each display to a _single_
  943. application context and then XtCloseDisplay() to shutdown each display
  944. and remove it from the application context.
  945.  
  946. The real problems occur when trying to close down a display.  This can
  947. happen 3 ways:
  948.     1. User selects a "quit" button on one of the displays,
  949.     2. User has window manager send a WM_DELETE_WINDOW message,
  950.     3. Server disconnect -- possibly from a KillClient message,
  951.        server shutdown/crash, or network failure.
  952.  
  953. I'll assume you can deal gracefully with 1 & 2 since it is _merely_ a
  954. problem of translating a Widget to a display and removing that
  955. display.  If not, then read the Oliver Jones article.
  956.  
  957. The third one is difficult to handle.  The following is based on the
  958. Oliver Jones article and I include it here because it is a difficult
  959. problem.
  960.  
  961. The difficulty arises because the Xlib design presumed that an I/O
  962. error is always unrecoverable and so fatal.  This is essentially true
  963. for a single display X based application, but not true for a
  964. multiple display program or an application that does things other than
  965. display information on an X server.  When an X I/O error occurs the
  966. I/O error handler is called and _if_ it returns then an exit()
  967. happens.  The only way around this is to use setjmp/longjmp to avoid
  968. returning to the I/O error handler.  The following code fragment
  969. demonstrates this:
  970.  
  971. #include <setjmp.h>
  972. jmp_buf XIOrecover;
  973.  
  974. void
  975. XIOHandler (dpy)
  976.     Display        *dpy;
  977. {
  978.     destroyDisplay (dpy);
  979.     longjmp (XIOrecover, 1);
  980. }
  981.  
  982. main ()
  983. {
  984.     ...
  985.     if (setjmp (XIOrecover) == 0)
  986.         XSetIOErrorHandler (XIOHandler);
  987.     XtAppMainLoop (app_context);
  988. }
  989.  
  990. The destroyDisplay() is something that given a Display pointer can go
  991. back to the application specific data and perform any necessary
  992. cleanup.  It should also call XtCloseDisplay().
  993.  
  994. For those of you unfamiliar with setjmp/longjmp, when setjmp() is
  995. first called it returns a 0 and save's enough information in the
  996. jmp_buf that a latter execution of longjmp() can return the program to
  997. the same state as if the setjmp() was just executed.  The return value
  998. of this second setjmp() is the value of the second argument to
  999. longjmp().  There are several caveats about using these but for this
  1000. purpose it is adequate.
  1001.  
  1002. Some other problems you might run into are resource converters that
  1003. improperly cache resources.  The most likely symptoms are Xlib errors
  1004. such as BadColor, BadAtom, or BadFont.  There may be problems with the
  1005. total number of displays you can open since typically only a limited
  1006. number of file descriptors are available with 32 being a typical
  1007. value.  You may also run into authorization problems when trying to
  1008. connect to a display.
  1009.  
  1010. There was much discussion in comp.windows.x about this topic in
  1011. November of 91.  Robert Scheifler posted an article which basically
  1012. said this is the way it will be and Xlib will not change.
  1013.  
  1014. ----------------------------------------------------------------------
  1015. 19. What changed from R3 to R4 to R5?
  1016. ----------------------------------------------------------------------
  1017.  
  1018. This addresses only changes in the Intrinsics.  First, the general
  1019. changes for each release are described.  Then a, certainly incomplete,
  1020. list of new functions added and others that are now deprecated are
  1021. listed.  Brevity is a primary goal.
  1022.  
  1023. Much of the following information is retrieved from Chapter 13 of the MIT
  1024. Xt Intrinsics Manual and from O'Reilly Volume 5, 3rd edition.
  1025.  
  1026. From R3 to R4
  1027. - Addition of gadgets (windowless widgets)
  1028. - New resource type converter interface to handle cacheing and
  1029.   additional  data.
  1030. - Variable argument list interface.
  1031. - #define XtSpecificationRelease 4  (added with this release)
  1032. - WMShellPart, TopLevelShellPart & TransientShellPart changed
  1033.   incompatibly.
  1034. - core.initialize, core.set_values added ArgList and count parameters
  1035. - event handlers had continue_to_dispatch parameter added
  1036. - core.set_values_almost specification changed.
  1037. - core.compress_exposure changed to an enumerated data type from Boolean
  1038. - core.class_inited changed to enumerated data type from Boolean
  1039. - constraint.get_values_hook added to extension record
  1040. - core.initialize_hook obsolete as info is passed to core.initialize
  1041. - shell.root_geometry_manager added to extension record
  1042. - core.set_values_hook obsolete as info is passed to core.set_values
  1043. - Calling XtQueryGeometry() must store complete geometry.
  1044. - Added UnrealizeCallback.
  1045. - XtTranslateCoords() actually works under R4.
  1046.  
  1047. From R4 to R5:
  1048. - Psuedo resource baseTranslation added.
  1049. - Searching for app-default, and other files, made more flexible
  1050. - customization resource added.
  1051. - Per-screen resource database.
  1052. - Support permanently allocated strings.
  1053. - Permanetly allocated strings required for several class fields.
  1054. - The args argument to XtAppInitialize, XtVaAppInitialize,
  1055.   XtOpenDisplay, XtDisplayInitialize, and XtInitialize were changed
  1056.   from Cardinal* to int*
  1057. - Many performance improvements (this is summarized from the article
  1058.   "Xt Performance Improvements in Release 5" by Gabe Beged-Dov in "The
  1059.   X Resource", Issue 3):
  1060.     - XrmStringToQuark() augmented with XrmPermStringToQuark() to
  1061.       avoid string copies.  Several fields in the class record are
  1062.       indicated as needing permanent strings.
  1063.     - Using an array of Strings for resources
  1064.     - Callback lists redesigned to use less memory
  1065.     - Translation manager redesigned and rewritten so it takes
  1066.       less memory, translation tables merges are faster, cache of
  1067.       action bindings
  1068.     - Keycode to Keysyms are cached.
  1069.     - Better sharing of GC's with modifiable fields
  1070.     - Window to Widget translation uses less space and faster
  1071.     - Does not malloc space for widget name since quark is available
  1072.     - Widget space is allocated to include the constraints
  1073.     - Over several example programs, about a 26% reduction in
  1074.       memory usage.
  1075.  
  1076. Functions new with R5:
  1077. ----------------------
  1078. XtAllocateGC()        - sharable GC with modifiable fields  
  1079. XtGetActionList()    - get the action table of a class
  1080. XtScreenDatabase()    - return resource database for a screen
  1081. XtSetLanguageProc()    - register language procedure called to set locale
  1082.  
  1083.  
  1084. Functions new with R4:
  1085. ----------------------
  1086. XtAppAddActionHook()    - procedure to call before _every_ action.
  1087. XtAppInitialize()    - lots of initialization work.
  1088. XtAppReleaseCacheRefs()    - decrement cache reference count for converter
  1089. XtAppSetFallbackResources() - specify default resources
  1090. XtAppSetTypeConverter()    - register a new style converter
  1091. XtCallCallbackList()    - directly execute a callback list
  1092. XtCallConverter    ()    - invoke a new style converter
  1093. XtCallbackReleaseCacheRef() - release a cached resource value
  1094. XtCallbackReleaseCacheRefList() - release a list of cached resource values
  1095. XtConvertAndStore()    - find and call a resource converter
  1096. XtDirectConvert()    - Invoke old-style converter
  1097. XtDisplayOfObject()    - Return the display
  1098. XtDisplayStringConversionWarning() - issue a warning about conversion
  1099. XtFindFile()        - Find a file
  1100. XtGetActionKeysym()    - Retrieve keysym & modifies for this action
  1101. XtGetApplicationNameAndClass() - return name and class
  1102. XtGetConstraintResourceList() - get constraints for a widget
  1103. XtGetKeysymTable()    - return keycode-to-keysym mapping table
  1104. XtGetMultiClickTime()    - read the multi-click time
  1105. XtGetSelectionRequest()    - retrieve the SelectionRequest event
  1106. XtGetSelectionValueIncremental() - obtain the selection value incrementally
  1107. XtGetSelectionValuesIncremental() - obtain the selection value incrementally
  1108. XtInitializeWidgetClass() - initialize a widget class manually
  1109. XtInsertEventHanlder()    - register event handler before/after others
  1110. XtInsertRawEventHandler() - register event handler without modify input mask
  1111. XtIsObject()        - test if subclass of Object
  1112. XtIsRectObj()        - test if subclass of RectObj
  1113. XtKeysymToKeyCodeList()    - return list of keycodes
  1114. XtLastTimestampProcessed() - retrieve most recent event time
  1115. XtMenuPopdown        - Action for popping down a widget
  1116. XtMenuPopup        - Action for popping up a widget
  1117. XtOffsetOf        - macro for structure offsets
  1118. XtOwnSelectionIncremental() - make selection data availabe incrementally
  1119. XtPoupSpringLoaded()    - map a spring-loaded popup
  1120. XtRegisterGrabAction()    - indicate action procedure needs a passive grab
  1121. XtRemoveActiohHook()    - remove function called after every action
  1122. XtResolvePathname()    - find a file
  1123. XtScreenOfObject()    - return screen of object.
  1124. XtSetMultiClickTime()    - set the multi-click time
  1125. XtSetWMColormapWindows() - set WM_COLORMAP_WINDOWS for custom colormaps
  1126. XtUngrabButton()    - cancel a passive button grab
  1127. XtUngrabKey()        - cancel a passive key grab
  1128. XtUngrabKeybard()    - release an active keyboard grab
  1129. XtUngrabPointer()    - release an active pointer grab
  1130. XtVa*()            - varags interfaces to a bunch of functions
  1131. XtWindowOfObject()    - return Window of nearest widget ancestor
  1132.  
  1133.  
  1134. Deprecated        Replacement            When
  1135. ----------------------------------------------------------------------
  1136. XtAddActions()        XtAppAddActions()        R3
  1137. XtAddConverter()    XtAppAddConverter()        R3
  1138. XtAddInput()        XtAppAddInput ()        R3
  1139. XtAddTimeout()        XtAppAddTimeout()        R3
  1140. XtAddWorkProc()        XtAppAddWorkProc()        R3
  1141. XtConvert()        XtConvertAndStore()        R4
  1142. XtCreateApplicationShell XtAppCreateShell()        R3
  1143. XtDestroyGC()        XtReleaseGC()            R3
  1144. XtError()        XtAppError()            R3
  1145. XtGetErrorDatabase()    XtAppGetErrorDatabase        R3
  1146. XtGetErrorDatabaseText() XtAppGetErrorDatabaseText    R3
  1147. XtGetSelectionTimeout()    XtAppGetSelectionTimeout    R3
  1148. XtInitialize()        XtAppInitialize()        R3
  1149. XtMainLoop()        XtAppMainLoop()            R3
  1150. MenuPopdown(action)    XtMenuPopdown(action)        R4
  1151. MenuPopup(action)    XtMenuPopup(action)        R4
  1152. XtNextEvent()        XtAppNextEvent()        R3
  1153. XtPeekEvent()        XtAppPeekEvent()        R3
  1154. XtPending()        XtAppPending()            R3
  1155. XtSetErrorHandler()    XtAppSetErrorHandler()        R3
  1156. XtSetErrorMsgHandler    XtAppSetErrorMsgHandler()    R3
  1157. XtSetSelectionTimeout()    XtAppSetSelectionTimeout()    R3
  1158. XtSetWarningHandler()    XtAppSetWarningHandler()    R3
  1159. XtSetWarningMsgHandler() XtAppSetWarningMsgHandler()    R3
  1160. XtWarning()        XtAppWarning()            R3
  1161. XtWarningMsg()        XtAppWarningMsg()        R3
  1162.  
  1163. ----------------------------------------------------------------------
  1164. 20. Where are the resources loaded from?
  1165. ----------------------------------------------------------------------
  1166.  
  1167. The resources of a widget are filled in from the following places
  1168. (from highest priority to lowest priority):
  1169.  
  1170.     1. Args passed at creation time.
  1171.     2. Command line arguments.
  1172.     3. User's per host defaults file
  1173.     4. User's defaults file.
  1174.     5. User's per application default file.
  1175.     6. System wide per application default file.
  1176.  
  1177. Note that 2-6 are read only once on application startup.  The result
  1178. of steps 3-6 is a single resource database used for further queries.
  1179.  
  1180. The per host defaults file contains customizations for all
  1181. applications executing on a specific computer.  This file is either
  1182. specified with the XENVIRONMENT environment variable or if that is not
  1183. set then the file $HOME/.Xdefaults-<host> is used.
  1184.  
  1185. The user defaults file is either obtained from the RESOURCE_MANAGER
  1186. property on the root window of the display or if that is not set then
  1187. the file $HOME/.Xdefaults is used.  Typically, the program "xrdb" is
  1188. used to set the RESOURCE_MANAGER property.  Please note that this
  1189. should be kept relatively small as each client that connects to the
  1190. display must transfer the property.  A size of around 1-3KByte is
  1191. reasonable.  Some toolkits may track changes to the RESOURCE_MANAGER
  1192. but most do not.
  1193.  
  1194. A user may have many per application default files containing
  1195. customizations specific to each application.  The intrinsics are quite
  1196. flexible on how this file is found.  Read the next part that describes
  1197. the various environment variables and how they effect where this file
  1198. is found.
  1199.  
  1200. The system wide per application default files are typically found in
  1201. /usr/lib/X11/app-defaults.  If such a file is not found then the
  1202. fallback resources are used.  The intrinsics are quite flexible on how
  1203. this file is found.  Read the next part that describes the various
  1204. environment variables and how they effect where this file is found.
  1205.  
  1206. [Thanks to Oliver Jones (oj@pictel.com) for the following, 6/92]
  1207.  
  1208. You can use several environment variables to control how resources are
  1209. loaded for your Xt-based programs -- XFILESEARCHPATH,
  1210. XUSERFILESEARCHPATH, and XAPPLRESDIR.  These environment variables
  1211. control where Xt looks for application-defaults files as an
  1212. application is initializing.  Xt loads at most one app-defaults file
  1213. from the path defined in XFILESEARCHPATH and another from the path
  1214. defined in XUSERFILESEARCHPATH.
  1215.  
  1216. Set XFILESEARCHPATH if software is installed on your system in such a
  1217. way that app-defaults files appear in several different directory
  1218. hierarchies.  Suppose, for example, that you are running Sun's Open
  1219. Windows, and you also have some R4 X applications installed in
  1220. /usr/lib/X11/app-defaults. You could set a value like this for
  1221. XFILESEARCHPATH, and it would cause Xt to look up app-defaults files
  1222. in both /usr/lib/X11 and /usr/openwin/lib (or wherever your
  1223. OPENWINHOME is located):
  1224.  
  1225.     setenv XFILESEARCHPATH /usr/lib/X11/%T/%N:$OPENWINHOME/lib/%T/%N
  1226.  
  1227. The value of this environment variable is a colon-separated list of
  1228. pathnames.  The pathnames contain replacement characters as follows
  1229. (see XtResolvePathname()):
  1230.  
  1231.     %N    The value of the filename parameter, or the
  1232.         application's class name.
  1233.     %T    The value of the file "type".  In this case, the
  1234.         literal string "app-defaults"
  1235.     %C    customization resource (R5 only)
  1236.     %S    Suffix.  None for app-defaults.
  1237.     %L    Language, locale, and codeset (e.g. "ja_JP.EUC")
  1238.     %l    Language part of %L  (e.g. "ja")
  1239.     %t    The territory part of the display's language string
  1240.     %c    The codeset part of the display's language string
  1241.  
  1242. Let's take apart the example.  Suppose the application's class name is
  1243. "Myterm". Also, suppose Open Windows is installed in /usr/openwin.
  1244. (Notice the example omits locale-specific lookup.)
  1245.  
  1246.     /usr/lib/X11/%T/%N        means /usr/lib/X11/app-defaults/Myterm
  1247.     $OPENWINHOME/lib/%T/%N    means /usr/openwin/lib/app-defaults/Myterm
  1248.  
  1249. As the application initializes, Xt tries to open both of the above
  1250. app-defaults files, in the order shown.  As soon as it finds one, it
  1251. reads it and uses it, and stops looking for others.  The effect of
  1252. this path is to search first in /usr/lib/X11, then in /usr/openwin.
  1253.  
  1254. Let's consider another example. This time, let's set
  1255. XUSERFILESEARCHPATH so it looks for the file Myterm.ad in the current
  1256. working directory, then for Myterm in the directory ~/app-defaults.
  1257.  
  1258.     setenv XUSERFILESEARCHPATH ./%N.ad:$HOME/app-defaults/%N
  1259.  
  1260. The first path in the list expands to ./Myterm.ad.  The second expands
  1261. to $HOME/app-defaults/Myterm.  This is a convenient setting for
  1262. debugging because it follows the Imake convention of naming the
  1263. app-defaults file Myterm.ad in the application's source directory, so
  1264. you can run the application from the directory in which you are
  1265. working and still have the resources loaded properly.
  1266.  
  1267. NOTE: when looking for app-default files with XUSERFILESEARCHPATH,
  1268.       for some  bizarre reason, neither the type nor file suffix is
  1269.       defined so %T and %S are useless.
  1270.  
  1271. With R5, there's another twist.  You may specify a customization
  1272. resource value.  For example, you might run the "myterm" application
  1273. like this:
  1274.  
  1275.     myterm -xrm "*customization: -color"
  1276.  
  1277. If one of your pathname specifications had the value
  1278. "/usr/lib/X11/app-defaults/%N%C" then the expanded pathname would be
  1279. "/usr/lib/X11/app-defaults/Myterm-color" because the %C substitution
  1280. character takes on the value of the customization resource.
  1281.  
  1282. The default XFILESEARCHPATH, compiled into Xt, is:
  1283.  
  1284.         /usr/lib/X11/%L/%T/%N%C:\  (R5)
  1285.         /usr/lib/X11/%l/%T/%N%C:\  (R5)
  1286.         /usr/lib/X11/%T/%N%C:\     (R5)
  1287.         /usr/lib/X11/%L/%T/%N:\
  1288.         /usr/lib/X11/%l/%T/%N:\
  1289.         /usr/lib/X11/%T/%N
  1290.  
  1291. (Note: some sites replace /usr/lib/X11 with a ProjectRoot in this
  1292. batch of default settings.)
  1293.  
  1294. The default XUSERFILESEARCHPATH, also compiled into Xt, is 
  1295.  
  1296.         <root>/%L/%N%C:\  (R5)
  1297.         <root>/%l/%N%C:\  (R5)
  1298.         <root>/%N%C:\     (R5)
  1299.         <root>/%L/%N:\
  1300.         <root>/%l/%N:\
  1301.         <root>/%N:
  1302.  
  1303. <root> is either the value of XAPPLRESDIR or the user's home directory
  1304. if XAPPLRESDIR is not set.  If you set XUSERFILESEARCHPATH to some
  1305. value other than the default, Xt ignores XAPPLRESDIR altogether.
  1306.  
  1307. Notice that the quick and dirty way of making your application find
  1308. your app-defaults file in your current working directory is to set
  1309. XAPPLRESDIR to ".", a single dot.  In R3, all this machinery worked
  1310. differently; for R3 compatibilty, many people set their XAPPLRESDIR
  1311. value to "./", a dot followed by a slash.
  1312.  
  1313.  
  1314. ----------------------------------------------------------------------
  1315. 21. What order are callbacks executed in?
  1316. ----------------------------------------------------------------------
  1317. (Courtesy of Donna Converse, converse@expo.lcs.mit.edu; 5/10/92)
  1318.  
  1319. The Intrinsics library do not guarantee an order.  This is because
  1320. both the widget writer and the application writer have the ability to
  1321. modify the entire contents of the callback list.  Neither one
  1322. currently knows what the other is doing and so the Intrinsics cannot
  1323. guarantee the order of execution.
  1324.  
  1325. The application programmer cannot rely on the widget writer; the
  1326. widget writer is not required to document when the widget will add and
  1327. remove callbacks from the list or what effect this will have;
  1328. therefore the functionality contained in a callback should be
  1329. independent of the functionality contained in other callbacks on the
  1330. list.
  1331.  
  1332. Even though the Xt standard in the definition of XtAddCallback
  1333. says:
  1334.  
  1335.      "callback_name: Specifies the callback list to which the
  1336.      procedure is to be appended."
  1337.  
  1338. you may not infer from the word "appended" that the callback routines
  1339. are called in the same order as they have been added to the callback
  1340. list.
  1341.  
  1342. ----------------------------------------------------------------------
  1343. 22. How do I know if a widget is visible?
  1344. ----------------------------------------------------------------------
  1345. (Courtesy of Donna Converse, converse@expo.lcs.mit.edu; 5/14/92)
  1346.  
  1347. > I am building a widget needs to know if it is visible. I set the visible
  1348. > interest field in Core and if my window is completely obscured, the Core
  1349. > visible flag goes FALSE. However, if my window is iconified, the flag
  1350. > stays set to TRUE.
  1351.  
  1352. Right, everything is implemented correctly.  This demonstrates a "deficiency"
  1353. in the X protocol, and the Core widget is reflecting the capabilities of the
  1354. protocol.  (The "deficiency" is that the information is available in one way,
  1355. in this case an inconvenient way.)  The Xt specification is accurate, in
  1356. the second and third paragraphs of section 7.10.2, so read this section
  1357. carefully.  The visible field will not change in response to iconification.
  1358.  
  1359. A VisibilityNotify event will not be received when the window goes from
  1360. viewable to unviewable, that is, when the widget or an ancestor is unmapped;
  1361. that is, when iconification occurs.  This is the protocol deficiency.
  1362. Visibility state and viewable state have specific meanings in the X protocol;
  1363. see the glossary in your Xlib and X protocol reference manual.
  1364.  
  1365. > Is this a problem with "mwm" or is there something
  1366. > else which needs to be done?
  1367.  
  1368. You'll see this with any window manager, with no window manager.
  1369.  
  1370. > If the problem is "mwm", what is the fastest
  1371. > way to determine if a window is iconified? 
  1372.  
  1373. As an application writer, keep track with a global Boolean in an action
  1374. routine with translations for MapNotify and UnmapNotify on the Shell widget
  1375. which contains your custom widget.  As the custom widget writer, see the
  1376. map_state field returned by a call to XGetWindowAttributes.  These are
  1377. suggestions.
  1378.  
  1379. ----------------------------------------------------------------------
  1380. 23. How do I reparent a widget in Xt, i.e. XtReparentWidget()?
  1381. ----------------------------------------------------------------------
  1382.  
  1383. You can't.
  1384.  
  1385. ----------------------------------------------------------------------
  1386. 24. Why use XtMalloc, XtFree, etc?
  1387. ----------------------------------------------------------------------
  1388.  
  1389. Unfortunately, most code that calls malloc(), realloc() or calloc()
  1390. tends to ignore the possibility of returning NULL.  At best it is
  1391. handled something like:
  1392.  
  1393.     ptr = (type *) malloc (sizeof (type))
  1394.     if (!ptr)
  1395.     {
  1396.         perror ("malloc in xyzzy()");
  1397.         exit (1)
  1398.     }
  1399. To handle this common case the Intrinsics define the functions
  1400. XtMalloc(), XtCalloc(), XtNew(), XtNewString() and XtRealloc() which
  1401. all use the standard C language functions malloc(), calloc() and
  1402. realloc() but execute XtErrorMsg() if a NULL value is returned.  Xt
  1403. error handlers are not supposed to return so this effectively exits.
  1404.  
  1405. In addition, if XtRealloc() is called with a NULL pointer, it uses
  1406. XtMalloc() to get the initial space.  This allows code like:
  1407.  
  1408.     if (!ptr)
  1409.         ptr = (type *) malloc (sizeof (type));
  1410.     else
  1411.         ptr = (type *) realloc (ptr, sizeof (type) * (count + 1));
  1412.     ++count;
  1413.  
  1414. to be written as:
  1415.  
  1416.     ptr = XtRealloc (ptr, sizeof (ptr) * ++count);
  1417.  
  1418. Also, XtFree() accepts a NULL pointer as an argument.  Generally, I've
  1419. found the Xt functions conveniant to use.  However, anytime I'm
  1420. allocating anything potentially large I use the standard functions so
  1421. I can fully recover from not enough memory errors.
  1422.  
  1423. XtNew() and XtNewString() are conveniant macros for allocating a
  1424. structure or copying a string:
  1425.  
  1426.       struct abc *xyzzy;
  1427.       char         *ptr;
  1428.       char         *str = "abcdef";
  1429.  
  1430.       xyzzy = XtNew (struct abc);    /* takes care of type casting */
  1431.       ptr = XtNewString (str);
  1432.  
  1433. Just to emphasize this, the Xt memory allocators are required to be
  1434. compatible and so interchangeable with the standard C library memory
  1435. allocators.
  1436.  
  1437. A common error for Motif programmers is to use XtFree() on a string
  1438. when they should really be using XmStringFree().
  1439.  
  1440. ----------------------------------------------------------------------
  1441. 25. How to debug an Xt application?
  1442. ----------------------------------------------------------------------
  1443. First, I'd recomend getting "purify" from Pure Software.  This is a
  1444. great package for tracing memory problems on Sun's.  It's a bit pricey
  1445. at $2750 but I'd still recomend it.  Excuse the marketing blurb
  1446. (contact support@pure.com for more info).
  1447.  
  1448.     Purify inserts additional checking instructions directly into
  1449.     the object code produced by existing compilers.  These
  1450.     instructions check every memory read and write performed by
  1451.     the program under test and detect several types of access
  1452.     errors, such as reading unitialized memory, writing past
  1453.     malloc'd bounds, or writing to freed memory.  Purify inserts
  1454.     checking logic into all of the code in a program, including
  1455.     third party and vendor object-code libraries, and verifies
  1456.     system call interfaces.  In addition, Purify tracks memory
  1457.     usage and identifies individual memory leaks using a novel
  1458.     adaption of garbage collection techniques.  Purify's nearly
  1459.     comprehensive memory access checking slows the target program
  1460.     down typically by a factor of two to five.
  1461.  
  1462. An alternative package that isn't as pricey ($395 for a Sun), runs on
  1463. many Unix's and has pretty similar features is "The SENTINEL Debugging
  1464. Environment".  This replaces malloc() and several other C library
  1465. functions to add additional checks.  (contact cpcahil@virtech.vti.com
  1466. for more info)
  1467.  
  1468. Next, if you are getting any sort of Xlib error, you'll need to run in
  1469. synchronous mode, easily accompished with the "-sync" command line
  1470. argument or by setting the variable Xdebug to 1 with your debugger.  Then
  1471. set a break point in exit().  This will let you trace back to the
  1472. original Xlib function being called.  If you don't run in synchronous
  1473. mode, then the actual error may have occured any number of calls to
  1474. Xlib previously since the Xlib calls are buffered and replies from the
  1475. server are asynchronous.
  1476.  
  1477. Next, if you are having trouble with window layout, you can use the
  1478. undocumented resource "xtIdentifyWindows" or the class resource
  1479. "XtDebug" to cause the widget name to be identified with each window.
  1480. For example:
  1481.  
  1482.     example% xload -xrm '*XtDebug:true' &
  1483.     example% xwininfo -tree
  1484.          <click in new xload window>
  1485.  
  1486. will give the normal information but the widget name and class of each
  1487. window is included.  This can help for checking the location and size
  1488. of errant widgets.
  1489.  
  1490. Next, if you are having trouble with geometry managers or you want to
  1491. test the way a widget manages it's children, you can try
  1492. export.lcs.mit.edu:contrib/libXtGeo.tar.Z.  This acts as a filter
  1493. between any children and a geometry manager and checks the behaviour
  1494. of both.  It's a very clever idea.
  1495.  
  1496. The most unfortunate problem is debugging a callback while the
  1497. application is executing a grab of the keyboard or mouse (such as from
  1498. a pulldown menu).  The server effectively locks up and you'll need to
  1499. go to another machine and kill the debugger manually.  The server
  1500. locks up because the application being debugged has said no one else
  1501. can have access to the keyboard but the application is not stopped
  1502. waiting because the debugger is waiting for your commands.
  1503. Unfortunately you can't give them because all the input is going to
  1504. your application which is stopped.
  1505.  
  1506. The best way to debug this kind of problem is with two machines on
  1507. your desk, running the program under a debugger (or other environment)
  1508. on one machine, and running the application on the other, possibly
  1509. using a command sequence like this:
  1510.  
  1511.     othermachine% xhost +thismachine
  1512.     thismachine% setenv DISPLAY othermachine:0;
  1513.     thismachine% gdb application    # Your favorite debugger.
  1514.     or this:
  1515.     othermachine% xhost +thismachine
  1516.     thismachine% gdb application
  1517.     (gdb) set environment DISPLAY othermachine:0
  1518.     (gdb) run ...
  1519.  
  1520. I believe CodeCenter, a C interpreter/graphical debugger has a method
  1521. of dealing with this by explicitely calling the Xlib functions to
  1522. release any grabs during breakpoints.
  1523.  
  1524. Debugging widget problems requires pretty good debugging skills and
  1525. knowledge of how widgets work.  You can go a long way without knowing
  1526. the internals of a particular widget but not very far without
  1527. understanding how a widget works.  Judicious use of conditional
  1528. breakpoints and adding print statements with the debugger help a great
  1529. deal.
  1530.  
  1531. ----------------------------------------------------------------------
  1532. 26. Why don't XtAddInput(), XtAddTimeout() and XtAddWorkProc() work?
  1533. ----------------------------------------------------------------------
  1534.    I have got a delicate problem with the three routines XtAddInput,
  1535.    XtAddTimeOut and XtAddWorkProc. The problem I have is that when
  1536.    I use them in my application they seem not to be registred properly.
  1537.    I have made a handy little testprogram where everything works
  1538.    perfect, but in my "real" application nothing happens. 
  1539.  
  1540. The introduction in R3 of the XtApp*() functions obsoleted those
  1541. routines.  What happens is they use a default application context
  1542. different then the one you may have created.  Since events and
  1543. timeouts are distributed on a per application context basis and you
  1544. are using two application contexts, you won't get those events.
  1545.  
  1546. For example:
  1547.  
  1548.     ...
  1549.     cnt = 0;
  1550.     toplevel = XtAppInitialize(&app, class,
  1551.                    Desc, XtNumber (Desc),
  1552.                    &argc, argv,
  1553.                    Fallback, args, cnt);
  1554.  
  1555.     XtAddTimeOut (...)
  1556.     XtAddWorkProc (...)
  1557.  
  1558.     XtAppMainLoop (app)
  1559.  
  1560. would never invoke the timeout.
  1561.  
  1562.